import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Book } from './entities/book.entity';
import { In, Like, Not, Repository } from 'typeorm';
import { BookKeyAndAuth, BookTypes } from './enum/book-type.enum';

@Injectable()
export class BookService {
    constructor(
        @InjectRepository(Book)
        private readonly bookRepository: Repository<Book>
    ) {}
    
    async findAll(query, userid) {
        // 这一步可以拿到用户的id，根据id查询角色，然后在查询权限
        const getUserSQL = `select * from admin_user where id = ${userid}`
        const userRes = await this.bookRepository.query(getUserSQL)
        let { role } = userRes[0]
        role = JSON.parse(role)
        role = role.map(item => `'${item}'`)
        const permissionSQL = `SELECT * from permission where id in (
            SELECT DISTINCT permissionId from role_permission where roleId in (
                select id from role where name in (${role.join(',')}) 
            )
        )`
        const permissionRes = await this.bookRepository.query(permissionSQL)
        // 判断是否有看机密数据的数据权限（也就是图书的类型权限）
        const authKey = Object.keys(BookKeyAndAuth)
        const hasAuth = permissionRes.find(item => authKey.includes(item.key))
        const where:any = {}
        
        // 如果没有机密的数据权限
        if(!hasAuth) {
            // 添加条件以排除 type 等于 没有权限的key
            where.type = Not(In(Object.values(BookKeyAndAuth)));
        }
        if(query.fileName) {
            where.fileName = Like(`%${query.fileName}%`)
        }
        const { pageNum, pageSize } = query
        return this.bookRepository.findAndCount({
            skip:(pageNum - 1 ) * pageSize,
            take: pageSize,
            where
        });
    }
    findOne(id: number): Promise<Book | null> {
        return this.bookRepository.findOneBy({ id });
    }
    create(updateBookDto) {
        return this.bookRepository.save(updateBookDto);
    }
    update(updateBookDto) {
        if(updateBookDto.id) {
            return this.bookRepository.update(updateBookDto.id,updateBookDto);
        }
    }
    delete(id: number) {
        return this.bookRepository.delete(id);
    }
    getBookTypeSelect() { 
        return Promise.resolve(Object.entries(BookTypes).map(item => {
            return {
                label: item[1],
                value: item[0]
            }
        }))
    }
}
